package com.example.myapplication.markwon

import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.Spanned
import android.text.style.LeadingMarginSpan
import android.widget.TextView
import io.noties.markwon.core.MarkwonTheme
import io.noties.markwon.utils.LeadingMarginUtils

/**
 * Create by Tanzhenxing on 2025/7/1.
 * Description:
 */
class OrderedListItemSpan(
    private val theme: MarkwonTheme,
    private val number: String,
) : LeadingMarginSpan {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var margin: Int = 0

    override fun getLeadingMargin(first: Boolean): Int {
        return margin.coerceAtLeast(theme.blockMargin)
    }

    override fun drawLeadingMargin(
        c: Canvas?,
        p: Paint?,
        x: Int,
        dir: Int,
        top: Int,
        baseline: Int,
        bottom: Int,
        text: CharSequence?,
        start: Int,
        end: Int,
        first: Boolean,
        layout: Layout?
    ) {


        // if there was a line break, we don't need to draw anything
        if (!first
            || !LeadingMarginUtils.selfStart(start, text, this)
        ) {
            return
        }

        paint.set(p)

        theme.applyListItemStyle(paint)


        // if we could force usage of #measure method then we might want skip this measuring here
        // but this won't hold against new values that a TextView can receive (new text size for
        // example...)
        val numberWidth: Int = Math.max((paint.measureText(number) + .5f).toInt(), (paint.measureText( "99." + '\u00a0') + .5f).toInt())


        // @since 1.0.3
        var width = theme.blockMargin
        if (numberWidth > width) {
            // let's keep this logic here in case a user decided not to call #measure and is fine
            // with current implementation
            width = numberWidth
            margin = numberWidth
        } else {
            margin = 0
        }
        val left = if (dir > 0) {
            x + (width * dir) - numberWidth
        } else {
            x + (width * dir) + (width - numberWidth)
        }


        // @since 1.1.1 we are using `baseline` argument to position text
        c!!.drawText(number, left.toFloat(), baseline.toFloat(), paint)
    }
}